<template>
  <div class="console-secure">
    <el-select v-model="link" style="width: 25%;" placeholder="请选择" @change="getLink">
      <el-option v-for="(item, index) in linkOption" :key="index" :label="item.name" :value="item.site_id">
      </el-option>
    </el-select>
    <el-divider></el-divider>
    <el-row>
      <el-button type="primary" @click="addTask('20')">添加任务+</el-button>
     <el-button type="primary" @click="addTask('20')">定向采集+</el-button>
       <!-- <el-button type="primary" @click="goLexicon">私有词库管理</el-button>
      <el-button>批量添加任务</el-button>
      <el-button>应用到同组</el-button> -->
    </el-row>
    <el-form v-if="form.type != 0" label-position="top" label-width="80px" :model="form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="任务名称">
            <el-input size="small" v-model="form.name" placeholder="最多10个字"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="目标栏目">
            <el-input size="small" v-model="form.part" placeholder="目标栏目，自媒体随意"></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6">
          <el-form-item label="文章来源">
            <el-select v-model="form.type" style="width: 100%;" placeholder="请选择">
              <el-option label="私有词库" value="10"></el-option>
              <el-option label="定向采集" value="20"></el-option>
              <el-option label="公有词库" value="30"></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item>
            <div slot="label" style="visibility: hidden;">--</div>
            <el-button type="primary" @click="saveLexicon" :loading="sl_loading">保存</el-button>
            <el-button @click="form.type = 0">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row class="addTask" v-if="form.type == '10'">
        <el-col :span="8">
          <div class="title">已选词库（自动去重）</div>
          <div class="content">
            <div class="items">
              <el-checkbox-group v-model="hotLexicon1">
                <div class="item" v-for="(item,index) in lexiconList" :key="index">
                  <el-checkbox :label="item"></el-checkbox>
                  <div class="size" @click="showLexicon(item)">{{ item.size }}词</div>
                </div>
              </el-checkbox-group>
            </div>
          </div>
          <div style="margin-top: 1%;">
            <el-button size="mini" type="primary" @click="noBind">解绑</el-button>
            <el-button size="mini">全选</el-button>
            <el-button size="mini">反选</el-button>
            <el-button size="mini">取消</el-button>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="title">
            &nbsp;
            <span v-if="form.type == 30">公有词库</span><span v-if="form.type == 10">私有词库</span>
          </div>
          <div class="content">
            <div class="items">
              <el-checkbox-group v-model="hotLexicon">
                <div class="item" v-for="(item,index) in hotList" :key="index">
                  <el-checkbox :label="item"></el-checkbox>
                  <div class="size" @click="showLexicon(item)">{{ item.size }}词</div>
                </div>
              </el-checkbox-group>
            </div>
          </div>
          <div style="margin-top: 1%;">
            <el-button size="mini" type="primary" @click="bindLexicon">绑定</el-button>
            <el-button size="mini">全选</el-button>
            <el-button size="mini">反选</el-button>
            <el-button size="mini">取消</el-button>
          </div>
        </el-col>
      </el-row> -->
      <el-row v-if="form.type == '20'">
        <el-table :data="tableData1" :cell-style="{ 'height': '40px', 'padding': '8px 0' }"
        :header-cell-style="{'background-color': '#eef1ff','color': '#2c2c2c','border-radius': '10px'}">
          <el-table-column label="定向目标网址" prop="url" width="300">
          </el-table-column>
          <el-table-column prop="model" width="100" label="运行模式">
          </el-table-column>
          <el-table-column prop="page_range" width="100" label="翻页范围">
          </el-table-column>
          <el-table-column prop="rule_num" width="100" label="抓取规则">
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="setRule(scope.$index, scope.row)" :loading="scope.row.ruleSetLoading">规则设置</el-button>
              <el-button size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex;justify-content: center;margin-top: 1%;">
          <el-button size="mini" type="primary" @click="directional">跟踪采集+</el-button>
          <el-button size="mini" type="primary">单次采集+</el-button>
          <el-button size="mini">使用教程</el-button>
        </div>
      </el-row>
    </el-form>
    <div style="margin-top: 1%;" v-if="form.type == 0">
      <el-table :data="tableData" v-if="tableData && tableData.length > 0" v-loading="loading" style="width: 100%"
        :cell-style="{ 'height': '40px', 'padding': '8px 0' }" :header-cell-style="{'background-color': '#eef1ff','color': '#2c2c2c','border-radius': '10px'}">
        <el-table-column label="任务名称" prop="name" width="300" #default="scope">
          <span v-if="scope.row.type == 10" style="color: green;">[私有]{{ scope.row.name }}</span>
          <span v-if="scope.row.type == 20" style="color: blue;">[定向]{{ scope.row.name }}</span>
          <span v-if="scope.row.type == 30" style="color: yellow;">[公有]{{ scope.row.name }}</span>
        </el-table-column>
        <el-table-column align="center" prop="task_id" width="100" label="目标栏目ID">
        </el-table-column>
        <el-table-column align="center" prop="no_grab_num" label="待抓取">
        </el-table-column>
        <el-table-column align="center" prop="article_num" label="文章数">
        </el-table-column>
        <el-table-column align="center" prop="article_num" label="任务详情">
          <template slot-scope="scope">
            <div v-if="scope.row.items&&scope.row.items.length">
              <el-popover
                placement="bottom"
                width="600"
                trigger="hover">
                <el-table :data="scope.row.items">
                  <el-table-column align="center" prop="create_time" label="创建时间">
                  </el-table-column>
                  <el-table-column align="center" prop="url" label="任务地址">
                  </el-table-column>
                  <el-table-column align="center" label="操作">
                    <template slot-scope="text">
                      <el-button size="mini" type="primary" @click="editTask(text.row)">编辑</el-button>
                      <el-button size="mini" @click="delTask(text.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button type="text" slot="reference">查看详情</el-button>
              </el-popover>
            </div>
            <div v-else>暂无任务</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="status_error" label="状态详情">
          <template slot-scope="scope">
            <div class="status_error">{{ scope.row.status_error }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <!-- <div v-if="scope.row.status == 10">已启用</div>
            <div v-if="scope.row.status == 20">已禁用</div> -->
            <el-button size="mini" type="danger" plain v-if="scope.row.status == 10" icon="el-icon-check" @click="closeTask(scope.row)">已启用</el-button>
            <el-button size="mini" type="success" plain v-if="scope.row.status == 20" icon="el-icon-close" @click="startTask(scope.row)">已禁用</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="oneCropping(scope.row)">配置设置</el-button>
            <el-button size="mini" type="primary" @click="directional1(scope.row)">添加任务地址</el-button>
            <el-button size="mini" @click="delectTask(scope.row)">删除任务</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else>
        <span>请添加一个任务</span>
        <el-divider></el-divider>
      </div>
    </div>
    <!-- <div class="desc">
      <span>
        常见问题
        <br />任务名称和目标栏目ID怎么填？有什么影响？

        <br />1. 任务名称只是方便用户区分不同任务，只用于显示，不对采集行为产生任何影响。

        <br />2. 目标栏目ID主要针对网站用户，用于发布时将文章发到对应的栏目下，对自媒体用户没有影响。

        <br />3. 任务名称和目标栏目ID都允许重复添加。

        <br />WordPress栏目ID怎么看？

        <br />1. 在WordPress后台，在文章模块下找到分类菜单并打开。

        <br />2. 鼠标指向分类名称，查看浏览器左下角显示的链接，找到tag_ID=xxx，所显示的数字就是此栏目的ID。

        <br />为什么提示没有找到词库？

        <br />1. 私有词库是需要先到私有词库管理页面去上传词库，然后才能绑定到任务上的。

        <br />2. 公有词库可以直接在右侧黄色选框下方搜索框输入任意词进行搜索。

        <br />为什么有的任务采集到的文章很少？长期采集不到文章会怎么样？

        <br />1. 不同的关键词，网络上新增内容产生的速度不同。由于长期采集相同关键词，特别是关键词数量少、行业冷门、 指定目标网站、过滤条件苛刻等条件下，网络上能够找到的文章越来越少，采集效率就会逐步下降。

        <br />2. 系统后台会追踪每个站点、每个任务、每个词库的采集效率，当其效率低于某一阈值时，会被系统自动暂停。暂停操作优先对词库，其次对任务，最后对站点。

        <br />3. 不管是使用公有词库还是私有词库，都建议尽量多绑定关键词，几千上万甚至更多的关键词，对提升采集效率有明显效果。

        <br />如何采集指定网站、指定关键词的内容？

        <br />1. 创建任务时选择公有词库或私有词库，并绑定关键词。

        <br />2. 任务创建完成后，在任务后方点击“目标网站设置”按钮，把要指定采集的网站域名填入即可。

        <br />定向采集用来做什么？怎么操作？

        <br />1. 由于关键词采集只能采到网络上能搜出来的内容，而有些冷门的或最新的内容还没有被收录，或者找不到合适的关键词，就会无法采集。

        <br />2. 定向采集可以不用关键词、不经过搜索引擎，直接访问目标网址，去采集某个列表页的文章。

        <br />3. 它既可以跟踪某个固定页面上出现的新链接进行采集，也可以通过翻页把历史文章采出来。

        <br />4. 用户只需要输入要采集的目标网址，简单设置翻页，并鼠标点选要采集的网址，就可以实现自动采集。

        <br />如何采集热点新闻？

        <br />1. 系统实时跟踪百度、好搜热搜词库，存放在公有词库[A版]，词库名称为<<<热点新闻直采>>>。

          <br />2. 用户只需创建一个使用A版公有词库的任务，然后绑定该词库就可以采集热点新闻。
      </span>
    </div> -->
    <el-dialog :title="`${addOrEdit ? '添加':'编辑'}定向采集`" :visible.sync="dialogVisible" width="30%">
      <div>定向目标网址：</div>
      <div><el-input type="text" v-model="url" placeholder="最大长度500，不支持中文"></el-input></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="sub_loading">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="`${addOrEdit ? '添加':'编辑'}定向采集2`" :visible.sync="dialogVisible2" width="30%">
      <div>定向目标网址：</div>
      <div><el-input type="text" v-model="url" placeholder="最大长度500，不支持中文"></el-input></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel2">取 消</el-button>
        <el-button type="primary" @click="submit2" :loading="sub_loading">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="lexiconTitle+'预览'" :visible.sync="showDialog" width="30%">
      <div>
        <el-input
          type="textarea"
          :rows="20"
          placeholder="请输入内容"
          v-model="textarea">
        </el-input>
      </div>
    </el-dialog>
    <el-dialog title="[定向采集]链接选择器" :visible.sync="ruleVisible" width="70%">
      <iframes :url="url" :htmlData="htmlData" @submitData="submitData"></iframes>
    </el-dialog>
    <el-dialog :title="`配置设置`" :visible.sync="dialogVisibleCrop" width="30%">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="图片裁剪">
                <div class="cropping_images">
                    <span>上：</span><el-input class="cropping_images_input" type="number" v-model="ruleForm.top" placeholder="上"></el-input>
                    <span>下：</span><el-input class="cropping_images_input" type="number" v-model="ruleForm.bottom" placeholder="下"></el-input>
                </div>
                <div class="cropping_images" style="margin-top: 20px">
                    <span>左：</span><el-input class="cropping_images_input" type="number" v-model="ruleForm.left" placeholder="左"></el-input>
                    <span>右：</span><el-input class="cropping_images_input" type="number" v-model="ruleForm.right" placeholder="右"></el-input>
                </div>
                <span>（单位：像素或百分比）</span>
            </el-form-item>
       </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancelCrop">取 消</el-button>
            <el-button type="primary" @click="submitCrop" :loading="crop_loading">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import { list,day_list,addLexiconTask } from '@/api/example'
import { taskList,taskStart,taskClose,taskDelect,task_item, task_config_update } from "@/api/task";
import { getHtml } from "@/api/aiChange";
import iframes from "./iframe.vue";
export default {
  name: 'Secure',
  components: {
    iframes
  },
  data() {
    const generateData = _ => {
      const data = [];
      for (let i = 1; i <= 15; i++) {
        data.push({
          value: i,
          desc: `备选项 ${i}`,
          disabled: i % 4 === 0
        });
      }
      return data;
    };
    return {
      pageInfo: {
        size: 15,
        current: 1,
        total: 1
      },
      dialogVisible: false,
      dialogVisible2: false,
      ruleVisible: false,
      showDialog: false,
      addOrEdit: false,
      lexiconTitle: '',
      textarea: '',
      url: '',
      link: 0,
      input1: '',
      htmlData:'',
      index: 0,
      checkList: [],
      hotLexicon: [],
      hotLexicon1: [],
      lexiconList: [],
      hotList: null,
      num: 0,
      nums: 0,
      linkOption: [
      ],
      form: {
        type: '0'
      },
      tableData: [],
      tableData1: [],
      lexiconInfo: null,
      loading: false,
      data: generateData(),
      value: [],
      filterMethod(query, item) {
        return item.pinyin.indexOf(query) > -1;
      },
      itemDetail: {},
      sl_loading: false,
      sub_loading: false,
      ruleForm: {
          top: 1,
          bottom: 8,
          left: 1,
          right: 1
      },
      rules: {

      },
      dialogVisibleCrop: false,
      crop_loading: false,
      taskId: '',
      siteId: '',
      configId: ''
    }
  },
  created() {
    this.getOption()

  },
  mounted() {
    window.addEventListener('message', this.handleIframeMessage);
  },
  beforeDestroy() {
    window.removeEventListener('message', this.handleIframeMessage);
  },
  methods: {
    editTask(row) {
      console.log(row)
      this.addOrEdit = false
      this.dialogVisible = true
      this.itemDetail = row
      this.url = row.url
    },
    delTask(row) {
      this.$confirm('是否删除该任务地址?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        taskDel({taskItemId:row.task_item_id}).then(res=> {
          this.$message.success(res.message)
          this.getList()
        })
      }).catch(() => {
        console.log('cancel')
      })
    },
    cancel() {
      this.url = ''
      this.itemDetail = null
      this.dialogVisible = false
    },
    directional1(row) {
      console.log('row',row)
      this.addOrEdit = true
      this.dialogVisible = true
      this.itemDetail = row
    },
    // 配置裁剪
    oneCropping: function (row) {
        this.dialogVisibleCrop = true
        this.taskId = row.task_id,
        this.siteId = row.site_id,
        this.configId = row.config && row.config.config_id ? row.config.config_id : 0
        this.ruleForm = {
          top: row.config && row.config.config_info && row.config.config_info.top ? row.config.config_info.top : 1,
          bottom: row.config && row.config.config_info && row.config.config_info.bottom ? row.config.config_info.bottom : 8,
          left: row.config && row.config.config_info && row.config.config_info.left ? row.config.config_info.left : 1,
          right: row.config && row.config.config_info && row.config.config_info.right ? row.config.config_info.right : 1,
        }
    },
    // 裁剪参数确定
    submitCrop() {
        this.crop_loading = true
        let obj = {
            taskId: this.taskId,
            siteId: this.siteId,
            configInfo: {
                top: Number(this.ruleForm.top) || '',
                bottom: Number(this.ruleForm.bottom)|| '',
                left: Number(this.ruleForm.left) || '',
                right: Number(this.ruleForm.right) || '',
            }
        }
        console.log('33333333', this.configId, obj)
        task_config_update({form: obj}, this.configId).then(res => {
            console.log('2232323', res)
            this.dialogVisibleCrop = false
            this.crop_loading = false
            this.$message.success(res.message)
            this.getList()
        }).catch(err => {
            this.dialogVisibleCrop = false
            this.crop_loading = false
        })
    },
    // 裁剪参数取消
    cancelCrop: function () {
        this.dialogVisibleCrop = false
    },
    submit2() {
    //   let query = {
    //     form: {
    //     //   task_id: this.itemDetail.task_id,
    //       model: 10,
    //       url: this.url,
    //       page_range: 0
    //     }
    //   }
      this.tableData1.push({
          url: this.url,
          model: '跟踪模式',
          page_range: '不翻页',
          rule_num: 0,
          ruleSetLoading: false,
      })
      this.dialogVisible2 = false
      this.sub_loading = false
    },
    cancel2() {
      this.dialogVisible2 = false
    },
    submit() {
      this.sub_loading = true
      let query = {
        form: {
          task_id: this.itemDetail.task_id,
          model: 10,
          url: this.url,
          page_range: 0
        }
      }
    //   this.tableData1.push({
    //       url: this.url,
    //       model: '跟踪模式',
    //       page_range: '不翻页',
    //       rule_num: 0,
    //       ruleSetLoading: false,
    //   })
    //   this.dialogVisible = false
    //   this.sub_loading = false
      task_item(query).then(res => {
        console.log(res)
        this.$message.success(res.message)
        this.dialogVisible = false
        this.sub_loading = false
      }).catch(err => {
         this.sub_loading = false
      })
    },
    startTask(row) {
      taskStart({taskId:row.task_id}).then(res=> {
        this.$message.success(res.message)
        this.getList()
      })
    },
    closeTask(row) {
      taskClose({taskId:row.task_id}).then(res=> {
        this.$message.success(res.message)
        this.getList()
      })
    },
    delectTask(row) {
      console.log(row)
      this.$confirm('是否删除该任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        taskDelect({taskId:row.task_id}).then(res=> {
          this.$message.success(res.message)
          this.getList()
        })
      }).catch(() => {
        console.log('cancel')
      })
    },
    saveLexicon() {
      if (!this.form.name) {
        this.$message.error('请输入任务名称')
        return false
      }
        // if (this.lexiconList&&this.lexiconList.length) {
        this.sl_loading = true
        const param = {
          siteId: this.link,
          name: this.form.name,
          part: this.form.part,
          type: this.form.type,
          // lexiconId: this.lexiconInfo.lexicon_id,
          // words: this.lexiconList,
          status: 10
        }
        addLexiconTask({form:param}).then(res => {
          console.log(res)
          if (res.status == 200) {
            this.$message.success(res.message)
          }
          this.form.type = 0
          this.form.name = ''
          this.form.part = ''
          this.lexiconList = []
          this.sl_loading = false
          this.getList()
        }).catch(err => {
          this.sl_loading = false
        })
      // }
    },
    bindLexicon() {
      this.hotLexicon.map(item => {
        this.hotList.map(ite => {
          if (item == ite) {
            this.lexiconList.push(ite)
            this.hotList = this.hotList.filter(i => i !== item)
          }
        })
      })
      this.hotLexicon1 = []
    },
    noBind() {
      this.hotLexicon1.map(item => {
        this.lexiconList.map(ite => {
          if (item == ite) {
            this.hotList.push(ite)
            this.lexiconList = this.lexiconList.filter(i => i !== item)
          }
        })
      })
      this.hotLexicon = []
    },
    goLexicon() {
      this.$router.push('/console/example/lexicon')
    },
    handleIframeMessage(event) {
      console.log(event)
      // if (event.origin !== 'http://example.com') return; // 验证消息来源
      // if (event.data.message === 'elementClicked') {
      //   // 处理被点击元素的层级信息
      //   console.log(event.data.data);
      // }
    },
    directional() {
      console.log('1')
      this.dialogVisible2 = true
    },
    setRule(index,row) {
      this.index = index
      row.ruleSetLoading = true
      this.getHtml(row)
    //   this.ruleVisible = true
    },
    showLexicon(item) {
      this.showDialog = true
      this.lexiconTitle = item.name
      this.textarea = item.lexicon_info.join('\n')
    },
    getHtml(row) {
      getHtml({url: this.url}).then(res=> {
        console.log(res)
        this.ruleVisible = true
        this.htmlData = res.data.html;
        row.ruleSetLoading = false
        // document.getElementById('myIframe').contentWindow.document.write(this.htmlData)
      }).catch(err => {
        row.ruleSetLoading = false
      })
    },
    submitData(data) {
      this.ruleList = data.ruleList
      this.tableData1[this.index].rule_num = this.ruleList.length
      console.log(this.ruleList)
      this.ruleVisible = false
    },
    getOption() {
      const query = {
        search: '',
        status: '',
      }
      list(query).then(res => {
        this.linkOption = res.data.list.data
        if (this.$route.query.id) {
          this.link = Number(this.$route.query.id)
        } else {
          this.link = this.linkOption[0].site_id
        }
        this.getList()
      })
    },
    getList() {
      const query = {
        siteId: this.link,
      }
      taskList(query).then(res => {
        this.tableData = res.data.list.data
      })
    },
    addTask(num) {
      this.form.type = num
      this.getHot()
    },
    getHot() {
      day_list().then(res=> {
        this.hotList = res.data.info.lexicon_info
        this.lexiconInfo = res.data.info
      })
    },
    getLink(data) {
        console.log(data)
        this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.console-secure {
  padding: 20px;

  .el-divider--horizontal {
    margin: 10px 0;
  }

  .desc {
    margin-top: 40px;

    span {
      line-height: 2;
    }
  }

  .addTask {
    .el-col {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .title {
      font-size: 14px;
      margin-bottom: 10px;
    }

    .content {
      border: 1px solid #46a6ff;
      width: 400px;
      height: 500px;
      padding: 20px;
      border-radius: 4px;
      position: relative;
      overflow-y: scroll;
      .items {
        width: 100%;
        height: 100%;
        overflow-y: scroll;
      }
    }

  }
  .status_error{
    color: rgb(253, 30, 30)
  }
  .cropping_images{
        display: flex;
        .cropping_images_input{
            width: 150px;
            margin-right:20px;
        }
    }
}
</style>
